<!--
 * @Description: 顶部推荐群组件
 * @Author: Kerwin
 * @Date: 2024-09-13 17:52:57
 * @LastEditTime: 2025-04-02 16:33:20
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="c_mian" :class="{ 'slide-out':!show }">
    <template v-for="item in recommendGroup" :key="item?.id">
      <view class="cItem">
        <view class="avatar">
          <u-avatar :src="getImgFullPath(item?.avatar)" size="110" mode="square"></u-avatar>
        </view>
        <view class="content">
          <view class="nameBox">
            <text class="name">{{ item?.name }}</text>
            <text class="time">{{ dateFormat(new Date(item?.createTime * 1000), 'MM-dd') }}</text>
          </view>
          <view class="actions">
            <text class="tips">进群聊聊？</text>
            <view class="btns">
              <u-button type="success" style="margin-right: 20rpx;" ripple plain size="mini" @click="cancel(item)">
                取消</u-button>
              <u-button type="success"  size="mini" ripple @click="joinGroup(item)">进入</u-button>
            </view>
          </view>
        </view>
      </view>
    </template>
  </view>
</template>
  
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store'
import { getImgFullPath, dateFormat } from '@/utils'
import { timeDetia } from '@/utils/common'
import { route } from '@/utils/common';
import { socialApi } from '@/api'


const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

interface Group {
  id: number
  name: string
  avatar: string
  createTime: number
  remark: string
  chatGroupId: number
  joined: boolean
}

const props = defineProps({
  groupList: {
    type: Array as () => Group[],
    default: () => []
  }
})

async function toGroupChat(item: {
  type?: any
  chatGroupId: any
  id: any
  name?: any
}) {
  route({
    url: '/packageD/pages/chat/index',
    params: {
      targetId: item.chatGroupId,
      groupName: item.name,
      cid: item.id,
      type: 1
    }
  })
}
// 加入群
async function joinGroup(group: Group) {
  setRecommendGroup([group])
  uni.showLoading()
  const { code } = await socialApi.joinChatGroupCity({
    userId: userInfo.value.id,
    friendCircleId: group.id
  }).finally(() => uni.hideLoading())
  if (code === 200) {
    toGroupChat(group)
  }
}
// 取消加入
const show = ref(true)
function cancel(group: Group) {
  setRecommendGroup([group])
  show.value = false
}
// 把推荐群放入本地缓存
function setRecommendGroup(groupList: Group[]) {
  const recommendGroupList = uni.getStorageSync('recommendGroupList')
  if(recommendGroupList) {
    uni.setStorageSync('recommendGroupList', [...JSON.parse(recommendGroupList),...groupList])
  }else {
    uni.setStorageSync('recommendGroupList', JSON.stringify(groupList))
  }
}


const recommendGroup = ref<Group[]>([])
// 获取推荐群(这个接口如果用户已加入推荐群，则不会返回已加入的群数据)
async function getChatGroupCityByPosition(location: { latitude: number; longitude: number }) {
  uni.showLoading()
  const currentAddress = uni.getStorageSync('currentAddress')
  const { data } = await socialApi.getChatGroupCityByPosition({
    latitude: location.latitude,
    longitude: location.longitude,
    cityId: currentAddress?.cityId || null,
  }).finally(() => {
    uni.hideLoading()
  })
  console.log('拥有的群==》',data);
  
  if (data) {
    recommendGroup.value = data
  }
}
function getRecommendGroup() {
  const currentLocation = uni.getStorageSync('currentLocation')
  if (currentLocation) {
    getChatGroupCityByPosition(currentLocation)
  } else {
    uni.getLocation({
      type: 'gcj02',
      success(res) {
        if (res.errMsg == 'getLocation:ok') {
          const { latitude, longitude } = res
          const currentLocation = {
            latitude,
            longitude
          }
          uni.setStorageSync('currentLocation', currentLocation)
          getChatGroupCityByPosition(currentLocation)
        }
      },
      fail(res) {
        if (res.errMsg == 'getLocation:fail 此key每日调用量已达到上限') {
          uni.showToast({
            title: '今日定位调用量已达到上限',
            icon: 'none'
          })
        }
        if (res.errMsg == 'getLocation:fail auth deny') {
          uni.showModal({
            content: '检测到您没打开获取位置信息功能权限，是否去设置打开？',
            confirmText: '确认',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (res) => {
                    console.log('确定')
                  }
                })
              } else {
                console.log('取消')
                return false
              }
            }
          })
        }
      }
    })
  }
}
onMounted(() => {
  getRecommendGroup()
})

</script>
  
<style lang="scss" scoped>
@import '@/styles/helper.scss';

.slide-out {
  transform: translateX(100%);
  opacity: 0;
  height:0
}

.c_mian {
  transition: transform 0.5s ease, opacity 0.5s ease;

  .cItem {
    display: flex;
    width: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    background: #fff;

    .content {
      flex: 1;
      margin-left: 20rpx;

      .nameBox {
        display: flex;
        justify-content: space-between;

        .name {
          font-size: 30rpx;
          max-width: 340rpx;
          @include ellipsis;
        }

        .time {
          color: #999;
        }

        margin-bottom: 20rpx;
      }

      .actions {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 20rpx;

        .tips {
          color: #999;
        }
      }
    }
  }
}
</style>
  